exutils = require("express/lib/utils")
utils = require("./utils")
path = require("path")
fs = require("fs")
#io = require "socket.io"
crawl = require "./crawl"
db_path = "database"
ddb = "db.txt"

request = require 'request'
mime = require 'mime'
crawl = require "./crawl"
model = require("./model")
config = require "./config"
User = model.User
Invite = model.Invite
Post = model.Post
Tag = model.Tag
#sinaoauth = require("./thlogin/sina")

tucao = module.exports = (app)->
  #WebSocket TESTING
  #io = io.listen app
  #io.sockets.on "connection", (conn)->
  #  conn.emit "news", data: "Hello World"
  #  conn.on "o", (data)->
  #    console.log data

  #sinaoauth(app)
#app.get("/data", function(req, res) {
#    //db.Init();
#    var f = new db.User();
#    f.find(function(err, ids){ 
#        console.log(ids); 
#        res.send(ids); 
#    });
#});
  
  mid_filter = (req, res, next)->
    u = req.session.user
    res.local("user", u) if u
    #console.log u?.date_create, typeof(u?.date_create)
    next()
      
  app.get "/signup/", mid_filter, (req, res)->
    return res.redirect "/" if req.session.user
    
    res.render "signup",
      invite: req.param "invite"

  app.post "/signup/", mid_filter, (req, res)->
    return res.redirect "/" if req.session.user

    invite_code = req.body.invite
    d = req.body
    Invite.all
      where:
        code: invite_code#.toUpperCase()
    , (err, icode)->
      #console.log typeof(icode[0].done), icode[0].done, icode[0].code
      if icode.length and icode[0].done == 0
        icode = icode[0]
        d.password = utils.sha256(d.password, config.SALT)
        u = new User d
        u.isValid (valid)->
          return res.render "signup", { form: utils.merge(u, {invite: invite_code}) } if not valid
          u.save (err, _u)->
            icode.user = _u.id
            icode.done = 1
            icode.save (err, i)->
              req.session.user = _u
              res.redirect "/"
      else
        d.errors =
          invite : "错误的激活码"
        return res.render "signup", { form: d}

  app.post "/signout/", mid_filter, (req, res)->
    delete req.session.user
    res.redirect req.header("Referer") or "/"

  app.post "/signin/", mid_filter, (req, res)->
    return res.redirect "/" if req.session.user
    
    d = req.body
    User.all
      where:
        email: d.email
        password: utils.sha256(d.password, config.SALT)
    , (err, u)->
      req.session.user = u[0] if u.length > 0
      res.redirect req.header("Referer") or "/"

  #app.get "/connect/qplus/", (req, res)->
  #  console.log req.query
  #  crawl.single "http://manhua.178.com/huoyingrenzhe/", (singles)->
  #    for page in singles
  #      page.url = utils.to_base64 page.url
  #    res.render "connect/qplus",
  #      single: singles

  #app.get "/connect/qplus/single/(:single)?", (req, res)->
  #  single = utils.to_str req.params.single
  #  console.log single
  #  crawl.pages single, (pages)->
  #    res.render "connect/qplus_single",
  #      pages: pages
  
  fetch_tags = utils.cache (callback)->
    Tag.all (err, tags)->
      console.log err if err
      tags.sort (a, b)-> a.date_create - b.date_create
      callback tags

  app.get "/", mid_filter, (req, res)->
    PAGE_COUNT = 50
    p = req.params.p|1
    fetch_tags (tags)->
      Post.all
        where:
          show: "show"
        , (err, posts)->
          console.log err if err
          PAGE_TOTAL = Math.round posts.length / PAGE_COUNT
          res.render "index",
            previous: `p > PAGE_COUNT ? PAGE_TOTAL : p <= 1 ? null : p-1`
            next: `p >= PAGE_COUNT-1 ? null : p <= 1 ? 2 : p+1`
            PAGE_TOTAL: PAGE_TOTAL
            p: p
            posts: posts[p-1*50..p*50]
            tags: tags

  app.get "/t/(:id)?", mid_filter, (req, res)->
    id = req.params.id?.toLowerCase()

    
    
    #fpath = if id then "#{db_path}/#{id}" else ddb
    #
    #fetch_nodes false, (nodes)->
    #  fs.readFile fpath, "utf-8", (err, data)->
    #      res.render "index",
    #          data: data or "",
    #          ischildroom: id and id.length > 0,
    #          openreg: false#true
    #          nodes: nodes[..5]
  
  app.post "/t/(:id)?", mid_filter, (req, res)->
    id = req.params.id?.toLowerCase()
    fpath = if id then "#{db_path}/#{id}" else ddb
    if req.body.ct?.trim().length == 0
      return res.redirect "/t/"+(id||"")
    ip = req.ip()
    addr = (utils.ip2adr(ip) || ip)
    if typeof addr == "object"
      addr = if addr.country == "CN" then addr.city else "#{addr.country} #{addr.city}"
    text = utils.ct_convert({ct: req.body.ct, ip:ip, addr:addr})
  
    fs.readFile fpath, "utf-8", (err, data)->
      fs.writeFile fpath, "#{text}\n#{data or ''}", "utf-8", (err, data)->
        fetch_tags true, (nodes)->
          res.redirect("/t/" + (id || ""))
  


  ## Utile Handler
  app.get "/api/fetch_image/", (req, res)->
    url = req.query.url
    callback = req.query.callback or "callback"
    if not url
      return res.send(404)
    mime_type = mime.lookup path.extname(url)[1..]
    request({url:url,encoding:"base64"}, (err, resp, body)->
      return res.send(404) if err
      res.header("Content-Type", "application/javascript")
      res.send("#{callback}('data:#{mime_type};base64,#{body}');")
    )

  ## Admin Handler
  admin_filter = (req, res, next)->
    return next() #if req.session.user?.email in ["soddyque@gmail.com"]
    res.redirect "/"

  app.get "/admin/", admin_filter, mid_filter, (req, res)->
    Invite.all
      where:
        done: "0"
      , (err, invites)->
        Tag.all (tag_err, tags)->
          res.render "admin/index",
            invites: invites
            tags: tags

  app.post "/admin/invite/new/", admin_filter, mid_filter, (req, res)->
    #Invite new Code
    count = req.body.invite_count | 0
    add_invite = ()->
      Invite.create
        code: utils.randstr(8).toUpperCase()
      , (err, code)->
        count++ if err
        if count--
          add_invite()
        else
          res.redirect "/admin/"
    add_invite()

  app.post "/admin/tag/new/", admin_filter, mid_filter, (req, res)->
    d = req.body
    t = new Tag d
    t.save validate:true, (err, t_ed)->
      console.log err if err
      fetch_tags true, (tags)->
        return res.redirect "/admin/"

  app.post "/admin/tag/hot/", admin_filter, mid_filter, (req, res)->
    d = req.body
    res.redirect "/admin/"
      
